# Thumbnailer - interface for image and video thumbnailers
# Copyright (C) 2008 Paul Hummer
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2008, Paul Hummer"
__author__ = "Paul Hummer <paul@ironlionsoftware.no.spam.com>"

import os

try:
    import hashlib
except ImportError:
    import md5

class ThumbnailerException(Exception): pass

class Thumbnailer(object):
    """ Thumbnailer interface for video and image thumbnailers. """
    
    MAX_SIZE = 512
    THUMB_QUALITY = 85
    
    def __init__(self, filename, type):

        thumb_dir = os.path.join(os.path.expanduser('~/.entertainer/cache/thumbnails'), type)
        self.filename = filename
        if hashlib:
            hash = hashlib.md5()
        else:
            hash = md5.new()
        hash.update(self.filename)
        self.filename_hash = hash.hexdigest()
        
        if not os.path.exists(self.filename):
            raise ThumbnailerException('File to thumbnail does not exist : %s' % self.filename)

        if os.path.exists(thumb_dir):
            if os.path.isfile(filename):
                self._thumb_file =  os.path.join(thumb_dir, self.filename_hash + '.jpg')
            else:
                raise ThumbnailerException('Thumbnailer filename is a folder : %s' % self.filename)
        else:
            raise ThumbnailerException('Unknown thumbnail type : %s' % type)
    
    def get_hash(self):
        return self.filename_hash

    def create_thumbnail(self):
        """
        Implement this method in deriving classes.
        
        Method should create a new thumbnail and save it to the Entertainer's
        thumbnail directory in JPEG format. Thumbnail filename should be a MD5
        hash of the absolute path of the original file.
        """
        abstract
